package cn.blnp.net.flowable.boot.service.impl;

import cn.blnp.net.flowable.boot.ext.cmd.TaskCarbonCopyCmd;
import cn.blnp.net.flowable.boot.service.TaskCarbonCopyService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <h3>任务知会（抄送）接口实现</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/20 10:22
 */
@Slf4j
@Service
@AllArgsConstructor
public class TaskCarbonCopyServiceImpl implements TaskCarbonCopyService {

    private ManagementService managementService;
    private TaskService taskService;
    private HistoryService historyService;
    
    @Override
    public void executeTaskCarbonCopy(String taskId, List<String> userIds) {
        //实例化任务知会Command类
        TaskCarbonCopyCmd taskCarbonCopyCmd = new TaskCarbonCopyCmd(taskId, userIds);
        //通过ManagementService管理服务执行任务知会Command类
        managementService.executeCommand(taskCarbonCopyCmd);
    }

    /**
     * <p><b>用途:查询运行时知会任务列表<b></p>
     * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
     * @since 10:24 2025/6/20
     * @params [userId] 
     * @param userId 
     * @return java.util.List<org.flowable.task.api.Task>
    **/
    @Override
    public List<Task> getCarbonCopyTasks(String userId) {
        List<Task> tasks = taskService.createNativeTaskQuery()
                .sql("select t1.* from ACT_RU_TASK t1 join ACT_RU_IDENTITYLINK t2 on "
                        + "t2.TASK_ID_=t1.ID_ and t2.TYPE_='carbonCopy' and "
                        + "t2.USER_ID_=#{userId}")
                .parameter("userId", userId).list();
        return tasks;
    }

    /**
     * <p><b>用途:查询历史知会任务列表<b></p>
     * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
     * @since 10:25 2025/6/20
     * @params [userId] 
     * @param userId 
     * @return java.util.List<org.flowable.task.api.history.HistoricTaskInstance>
    **/
    @Override
    public List<HistoricTaskInstance> getHistoricCarbonCopyTasks(String userId) {
        List<HistoricTaskInstance> tasks = historyService
                .createNativeHistoricTaskInstanceQuery()
                .sql("select * from ACT_HI_TASKINST t1 join ACT_HI_IDENTITYLINK t2 on "
                        + "t2.TASK_ID_=t1.ID_ and t2.TYPE_='carbonCopy' and t2.USER_ID_="
                        + "#{userId}")
                .parameter("userId", userId).list();
        return tasks;
    }
}
